package com.cn.shuangzi.ad.manager;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTFeedAd;
import com.bytedance.sdk.openadsdk.TTNativeAd;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationExpressRenderListener;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationAdEcpmInfo;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationBaseManager;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationNativeManager;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.KsErrorInfo;
import com.cn.shuangzi.ad.bean.YlhErrorInfo;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.ADUtil;
import com.cn.shuangzi.ad.util.FeedAdUtils;
import com.cn.shuangzi.ad.util.OnAdClosedListener;
import com.cn.shuangzi.ad.util.tt.TTAdManagerHolder;
import com.cn.shuangzi.ad.util.tt.UIUtils;
import com.cn.shuangzi.ad.view.AlertVipDialog;
import com.cn.shuangzi.util.SZUtil;
import com.qq.e.ads.cfg.DownAPPConfirmPolicy;
import com.qq.e.ads.cfg.VideoOption;

import java.util.List;

/**
 * 信息流
 */
public class AdNativeManager {
    private TTFeedAd mTTFeedAd = null;

    private Activity mActivity;
    private ViewGroup feedContainer;
    private Class<?> classVip;
    private OnAdClosedListener onAdClosedListener;

    public AdNativeManager(Activity activity, ViewGroup feedContainer) {
        this(activity, feedContainer, null, null);
    }

    public AdNativeManager(Activity activity, ViewGroup feedContainer, Class<?> classVip) {
        this(activity, feedContainer, classVip, null);
    }

    public AdNativeManager(Activity activity, ViewGroup bannerContainer, Class<?> classVip, OnAdClosedListener onAdClosedListener) {
        mActivity = activity;
        this.classVip = classVip;
        this.feedContainer = bannerContainer;
        this.onAdClosedListener = onAdClosedListener;
    }

    public TTFeedAd getFeedAd() {
        return mTTFeedAd;
    }

    public void loadAd(final String unitId, final int widthPx) {
        if (!TTAdManagerHolder.isInitSuccess()) {
            ADManager.getInstance().addOnAdInitDoneListener(new ADManager.OnAdInitDoneListener() {
                @Override
                public void onTTAdInitDone(boolean isSuccess) {
                    ADManager.getInstance().removeOnAdInitDoneListener(this);
                    if (isSuccess) {
                        loadAdReal(unitId, null, widthPx);
                    }
                }
            });
            ADManager.getInstance().initAd(true);
        } else {
            loadAdReal(unitId, null, widthPx);
        }
    }

    public void loadAd(final String unitId, final String scenarioId, final int widthPx) {
        if (!TTAdManagerHolder.isInitSuccess()) {
            ADManager.getInstance().addOnAdInitDoneListener(new ADManager.OnAdInitDoneListener() {
                @Override
                public void onTTAdInitDone(boolean isSuccess) {
                    ADManager.getInstance().removeOnAdInitDoneListener(this);
                    if (isSuccess) {
                        loadAdReal(unitId, scenarioId, widthPx);
                    }
                }
            });
            ADManager.getInstance().initAd(true);
        } else {
            loadAdReal(unitId, scenarioId, widthPx);
        }
    }

    private void loadAdReal(String mAdUnitId, String scenarioId, int widthPx) {
        feedContainer.removeAllViews();

        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(mAdUnitId)
                .setImageAcceptedSize(widthPx, 0) // 单位px
                .setAdCount(1) // 请求广告数量为1到3条 （优先采用平台配置的数量）
                .setMediationAdSlot(new MediationAdSlot.Builder().setScenarioId(scenarioId)
                        .setExtraObject(MediationConstant.KEY_GDT_VIDEO_OPTION,
                                new VideoOption.Builder()
                                        .setAutoPlayMuted(true)//gdt是否静音
                                        .setAutoPlayPolicy(VideoOption.AutoPlayPolicy.ALWAYS)
                                        .build())
                        .setScenarioId(scenarioId).setExtraObject(MediationConstant.KEY_GDT_MIN_VIDEO_DURATION, 1000)
//                        .setExtraObject(MediationConstant.KEY_GDT_MAX_VIDEO_DURATION,2000)
                        .setExtraObject(MediationConstant.KEY_GDT_DOWN_APP_CONFIG_POLICY, DownAPPConfirmPolicy.NOConfirm)
                        .build())
                .build();

        TTAdNative adNativeLoader = TTAdManagerHolder.getInstance().createAdNative(mActivity);
        adNativeLoader.loadFeedAd(adSlot, new TTAdNative.FeedAdListener() {
            @Override
            public void onError(int i, String s) {
                ADUtil.logError("信息流显示失败:" + s);
                clearData();
//                ADManager.getInstance().setYlhBannerAd(null);
//                ADManager.getInstance().setBannerYlhErrorInfo(null);
            }

            @Override
            public void onFeedAdLoad(List<TTFeedAd> list) {
                if (list != null && list.size() > 0) {
                    SZUtil.logError("信息流加载成功，" + list.size() + "条");
                    mTTFeedAd = list.get(0);
                    showFeedAd();
                }
            }
        });
    }

    public void clearData() {
        ADManager.getInstance().setNativeKsErrorInfo(null);
        ADManager.getInstance().setKsNativeAd(null);
        ADManager.getInstance().setKsFeedAd(null);
        ADManager.getInstance().setNativeYlhErrorInfo(null);
        ADManager.getInstance().setYlhNativeUnifiedADData(null);
        ADManager.getInstance().setYlhNativeExpressADView(null);
    }

    public void destroy() {
        clearData();
        try {
            if (getFeedAd() != null) {
                getFeedAd().destroy();
            }
            mActivity = null;
            mTTFeedAd = null;
            ADUtil.logError("信息流 destroy成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void showFeedAd() {
        if (mTTFeedAd == null) {
            SZUtil.logError("信息流广告已销毁，不显示信息流");
            return;
        }
        if(feedContainer==null||mActivity==null||mActivity.isFinishing()){
            SZUtil.logError("父容器已销毁，不显示信息流");
            return;
        }
        /** 5、展示广告 */
        // 绑定dislike
        mTTFeedAd.setDislikeCallback(mActivity, getDislikeCallback());
        MediationNativeManager manager = mTTFeedAd.getMediationManager();
        if (manager != null) {
            if (manager.isExpress()) {
                // --- 模板feed流广告
                SZUtil.logError("信息流，开始模板渲染");
                mTTFeedAd.setExpressRenderListener(getExpressAdInteractionListener());
                mTTFeedAd.render(); // 调用render方法进行渲染，在onRenderSuccess中展示广告
            } else {
                // --- 自渲染feed流广告
                SZUtil.logError("信息流，开始自渲染");
                // 自渲染广告返回的是广告素材，开发者自己将其渲染成view
                //FeedAdUtils详见下发示例代码
                View feedView = FeedAdUtils.getFeedAdFromFeedInfo(mTTFeedAd, mActivity, null, getAdInteractionListener());
                if (feedView != null) {
                    UIUtils.removeFromParent(feedView);
                    feedContainer.removeAllViews();
                    feedContainer.addView(feedView);
                }
            }
        }
    }

    private MediationExpressRenderListener getExpressAdInteractionListener() {
        return new MediationExpressRenderListener() {
            @Override
            public void onRenderFail(View view, String s, int i) {
            }

            @Override
            public void onAdClick() {
            }

            @Override
            public void onAdShow() {
//                if(mTTFeedAd!=null){
//                    printShowInfo(mTTFeedAd.getMediationManager());
//                }
                MediationAdEcpmInfo gmAdEcpmInfo = mTTFeedAd.getMediationManager().getShowEcpm();
                ADUtil.logError("展示的信息流广告信息： adSdkName: " + gmAdEcpmInfo.getSdkName() + "   CustomSdkName：" + gmAdEcpmInfo.getCustomSdkName() + "   Ecpm: " + gmAdEcpmInfo.getEcpm());

                if (gmAdEcpmInfo != null) {
                    if (!ADManager.getInstance().isYlhPlatform(gmAdEcpmInfo.getSdkName())) {
                        YlhErrorInfo ylhErrorInfo = ADManager.getInstance().getNativeYlhErrorInfo();
                        SZUtil.logError("优量汇准备上报竞价失败："+ylhErrorInfo);
                        if (ylhErrorInfo != null) {
                            if (ADManager.getInstance().getYlhNativeExpressADView() != null) {
                                int ecpm = getReportEcmp(ADManager.getInstance().getYlhNativeExpressADView().getECPM(), gmAdEcpmInfo.getEcpm());
                                ADManager.getInstance().getYlhNativeExpressADView().sendLossNotification(ecpm, ylhErrorInfo.getReason(), ylhErrorInfo.getAdnId());
                                ADUtil.logError("上报优量汇信息流竞价失败：ecpm=" + ecpm + "，" + ylhErrorInfo);
                            } else if (ADManager.getInstance().getYlhNativeUnifiedADData() != null) {
                                int ecpm = getReportEcmp(ADManager.getInstance().getYlhNativeUnifiedADData().getECPM(), gmAdEcpmInfo.getEcpm());
                                ADManager.getInstance().getYlhNativeUnifiedADData().sendLossNotification(ecpm, ylhErrorInfo.getReason(), ylhErrorInfo.getAdnId());
                                ADUtil.logError("上报优量汇信息流竞价失败：ecpm=" + ecpm + "，" + ylhErrorInfo);
                            }
                        }
                    }
                    if (!ADManager.getInstance().isKsPlatform(gmAdEcpmInfo.getSdkName())) {
                        KsErrorInfo ksErrorInfo = ADManager.getInstance().getNativeKsErrorInfo();
                        SZUtil.logError("快手准备上报竞价失败："+ksErrorInfo);
                        if (ksErrorInfo != null) {
                            if (ksErrorInfo.getAdExposureFailedReason() != null) {
                                if (ADManager.getInstance().getKsFeedAd() != null) {
                                    int ecpm = getReportEcmp(ADManager.getInstance().getKsFeedAd().getECPM(), gmAdEcpmInfo.getEcpm());
                                    ksErrorInfo.getAdExposureFailedReason().setWinEcpm(ecpm)
                                            .setAdnName(ADManager.getInstance().getReportKsAdnName(gmAdEcpmInfo.getSdkName()));
                                    ADManager.getInstance().getKsFeedAd().reportAdExposureFailed(ksErrorInfo.getAdExposureFailureCode(), ksErrorInfo.getAdExposureFailedReason());
                                    ADUtil.logError("上报快手信息流竞价失败：ecpm=" + ecpm + "，" + ksErrorInfo);
                                } else if (ADManager.getInstance().getKsNativeAd() != null) {
                                    int ecpm = getReportEcmp(ADManager.getInstance().getKsNativeAd().getECPM(), gmAdEcpmInfo.getEcpm());
                                    ksErrorInfo.getAdExposureFailedReason().setWinEcpm(ecpm)
                                            .setAdnName(ADManager.getInstance().getReportKsAdnName(gmAdEcpmInfo.getSdkName()));
                                    ADManager.getInstance().getKsNativeAd().reportAdExposureFailed(ksErrorInfo.getAdExposureFailureCode(), ksErrorInfo.getAdExposureFailedReason());
                                    ADUtil.logError("上报快手信息流竞价失败：ecpm=" + ecpm + "，" + ksErrorInfo);
                                }
                            }
                        }
                    }
                }

                clearData();
            }

            @Override
            public void onRenderSuccess(View view, float v, float v1, boolean b) {
                if (mTTFeedAd != null) {
                    View expressFeedView = mTTFeedAd.getAdView(); // *** 注意不要使用onRenderSuccess参数中的view ***
                    UIUtils.removeFromParent(expressFeedView);
                    feedContainer.removeAllViews();
                    feedContainer.addView(expressFeedView);
                }
            }
        };
    }

    private TTNativeAd.AdInteractionListener getAdInteractionListener() {
        return new TTNativeAd.AdInteractionListener() {
            @Override
            public void onAdClicked(View view, TTNativeAd ttNativeAd) {
            }

            @Override
            public void onAdCreativeClick(View view, TTNativeAd ttNativeAd) {
            }

            @Override
            public void onAdShow(TTNativeAd ttNativeAd) {
            }
        };
    }
    private AlertVipDialog alertVipDialog;
    private TTAdDislike.DislikeInteractionCallback getDislikeCallback() {
        return new TTAdDislike.DislikeInteractionCallback() {
            @Override
            public void onShow() {
            }

            @Override
            public void onSelected(int i, String s, boolean b) {
                // 用户点击dislike后回调
                SZUtil.logError("信息流dislike取消");
                if (classVip != null) {
                    if(alertVipDialog!=null&&alertVipDialog.isShowing()){
                        alertVipDialog.cancel();
                    }
                    alertVipDialog = new AlertVipDialog(mActivity, classVip);
                    alertVipDialog.show();
                }
                if (onAdClosedListener != null) {
                    onAdClosedListener.onAdClosed();
                }
                try {
                    if (getFeedAd() != null) {
                        getFeedAd().destroy();
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                mTTFeedAd = null;
            }

            @Override
            public void onCancel() {
                SZUtil.logError("信息Cancel流取消");

                if (classVip != null) {
                    if(alertVipDialog!=null&&alertVipDialog.isShowing()){
                        alertVipDialog.cancel();
                    }
                    alertVipDialog = new AlertVipDialog(mActivity, classVip);
                    alertVipDialog.show();
                }
                if (onAdClosedListener != null) {
                    onAdClosedListener.onAdClosed();
                }
                try {
                    if (getFeedAd() != null) {
                        getFeedAd().destroy();
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                mTTFeedAd = null;
            }
        };
    }

    public static void printShowInfo(MediationBaseManager adInfo) {
        SZUtil.logError("===参与竞价的信息流===");
        for (MediationAdEcpmInfo ecpm : adInfo.getMultiBiddingEcpm()) {
            if (ecpm != null) {
                logEcpmInfo(ecpm);
            }
        }

//        MediationBaseManager mediationManager = adInfo.getMediationManager();
        if (adInfo != null) {
            MediationAdEcpmInfo showEcpm = adInfo.getShowEcpm();
            if (showEcpm != null) {
                SZUtil.logError("===当前显示的信息流===");
                logEcpmInfo(showEcpm);
            }
        }
    }

    public static void logEcpmInfo(MediationAdEcpmInfo item) {
        SZUtil.logError("信息流，EcpmInfo: \n" +
                "SdkName: " + item.getSdkName() + ",\n" +
                "CustomSdkName: " + item.getCustomSdkName() + ",\n" +
                "SlotId: " + item.getSlotId() + ",\n" +
                // 单位：分；一般情况下兜底代码位的ecpm是0，若获取到的ecpm为0的话，可优先核实是否是兜底代码位
                "Ecpm: " + item.getEcpm() + ",\n" +
                "ReqBiddingType: " + item.getReqBiddingType() + ",\n" +
                "ErrorMsg: " + item.getErrorMsg() + ",\n" +
                "RequestId: " + item.getRequestId() + ",\n" +
                "RitType: " + item.getRitType() + ",\n" +
                "AbTestId: " + item.getAbTestId() + ",\n" +
                "ScenarioId: " + item.getScenarioId() + ",\n" +
                "SegmentId: " + item.getSegmentId() + ",\n" +
                "Channel: " + item.getChannel() + ",\n" +
                "SubChannel: " + item.getSubChannel() + ",\n" +
                "customData: " + item.getCustomData()
        );
    }

    private int getReportEcmp(int lossEcpm, String winEcpm) {
        int ecpm = lossEcpm;
        try {
            if (ecpm <= 0) {
                ecpm = 5 * ADConst.YUAN;
            }
            double preEcpm = Double.parseDouble(winEcpm);
            if (preEcpm > 0) {
                int addCPM = ADUtil.getRandom(2*ADConst.YUAN,80);
                ecpm = (int) (preEcpm + addCPM);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ecpm;
    }
}
